import json
from utils import device, format
from lib.server.http.fs import net_fs
from lib.config.index import server_config


async def return_ok(writer, path):
    response = (
        f"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: 14\r\n\r\n"
        + '{"value":"ok"}'
    )
    writer.write(response)


def create_route_headers(payload):
    content = json.dumps(payload)
    byte_data = bytes(content, "utf-8")
    length = len(byte_data)
    header_str = f"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {length}\r\n\r\n"
    return header_str


def create_route_response(payload):
    content = json.dumps(payload)
    byte_data = bytes(content, "utf-8")
    return byte_data


async def handle_routes(writer, path):
    if path == "/api/reboot":
        await return_ok(writer, path)
        await writer.drain()
        device.reboot()

    if path == "/api/projects":
        projects = net_fs.__projects
        res = {"projects": projects, "current": net_fs.__current_project["name"]}
        if server_config.is_debug():
            print("config projects:", res)
        writer.write(create_route_headers(res))
        writer.write(create_route_response(res))

    if "/api/change_project" in path:
        name = format.get_search_params(path, "name")
        if server_config.is_debug():
            print("http server change project to: ", name)
        if name:
            net_fs.set_current_project(name)
        else:
            net_fs.set_current_project("default")
        await return_ok(writer, path)

    if path == "/api/led_on":
        from lib.board.index import led

        led.on()
        await return_ok(writer, path)

    if path == "/api/led_off":
        from lib.board.index import led

        led.off()
        await return_ok(writer, path)

    if path == "/api/device_id":
        device_id = device.get_device_id()
        res = {"value": device_id}
        writer.write(create_route_headers(res))
        writer.write(create_route_response(res))

    if path == "/api/info":
        from lib.config.index import get_all_configs

        info = {"device_info": device.get_device_info()}
        configs = get_all_configs()
        info.update(configs)
        writer.write(create_route_headers(info))
        writer.write(create_route_response(info))
    await writer.drain()
